import json

import boto3


# 认证信息
class AwsAuthInfo:
    def __init__(self, aws_access_key_id, aws_secret_access_key):
        self.aws_access_key_id = aws_access_key_id
        self.aws_secret_access_key = aws_secret_access_key


# 各个区域的认证信息
aws_auth_map = {'cn-north-1': AwsAuthInfo('AKIAYSJKU5UZSXIGG4DH', 'Hb86FDa/0frhdwpY95AYiKIOczIzB60q9eFlPLtg'),
                'us-east-2': AwsAuthInfo('', ''),
                "eu-west-1": AwsAuthInfo('', '')}


def get_lambda_config(aws_region):
    try:
        aws_auth = aws_auth_map[aws_region]
        # 创建客户端
        client = boto3.client('lambda', region_name=aws_region,
                              aws_access_key_id=aws_auth.aws_access_key_id,
                              aws_secret_access_key=aws_auth.aws_secret_access_key)
        paginator = client.get_paginator('list_functions')
        lambda_functions = []

        for page in paginator.paginate():
            for function in page['Functions']:
                function_name = function['FunctionName']
                try:
                    # 获取Lambda函数的详细配置
                    config = client.get_function_configuration(
                        FunctionName=function_name
                    )
                    lambda_functions.append(config)
                except client.exceptions.ResourceNotFoundException:
                    print(f"Lambda function '{function_name}' not found.")
                except Exception as e:
                    print(f"An error occurred while fetching configuration for '{function_name}': {e}")
        return lambda_functions
    except Exception as e:
        print(f"Error: {e}")


if __name__ == '__main__':
    # 获取所有Lambda函数配置
    lambda_configs = get_lambda_config("cn-north-1")

    # 将配置信息写入JSON文件
    output_file = 'lambda_functions_config.json'
    try:
        with open(output_file, 'w') as f:
            json.dump(lambda_configs, f, indent=4)
        print(f"Lambda configurations have been saved to {output_file}")
    except IOError as e:
        print(f"Failed to write to file: {e}")